﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;
using Entity;
using Business;
using System.Web.UI;

namespace NetFlow
{
    public partial class TrafficAnalysis : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string filePath = Session["FilePath"].ToString(); // 替换为实际文件路径
                AnalysisBusiness analysisBusiness = new AnalysisBusiness();
                List<NetFlowEntity> netFlowList = analysisBusiness.ParseNetFlowData(filePath);

                // 对流量数据进行区间划分
                var trafficBuckets = DivideIntoBuckets(netFlowList);

                // 序列化数据
                string jsonData = new JavaScriptSerializer().Serialize(trafficBuckets);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ChartData", $"var trafficBuckets = {jsonData};", true);

                //Response.Write(jsonData);
            }
        }

        private Dictionary<string, int> DivideIntoBuckets(List<NetFlowEntity> netFlowList)
        {
            var trafficBuckets = new Dictionary<string, int>
            {
                { "0-100", 0 },
                { "101-200", 0 },
                { "201-300", 0 },
                { "301-400", 0 },
                { "401-500", 0 },
                { "500+", 0 }
            };

            foreach (var item in netFlowList)
            {
                long totalBytes = item.TotalBytes;
                if (totalBytes <= 100)
                {
                    trafficBuckets["0-100"]++;
                }
                else if (totalBytes <= 200)
                {
                    trafficBuckets["101-200"]++;
                }
                else if (totalBytes <= 300)
                {
                    trafficBuckets["201-300"]++;
                }
                else if (totalBytes <= 400)
                {
                    trafficBuckets["301-400"]++;
                }
                else if (totalBytes <= 500)
                {
                    trafficBuckets["401-500"]++;
                }
                else
                {
                    trafficBuckets["500+"]++;
                }
            }

            return trafficBuckets;
        }
    }
}